﻿# ----------------------------------------------------------- #
# Active Directory Domain Services (ADDS) User Configuration #
# ----------------------------------------------------------- #
param([string]$virtualMachineService, [string]$virtualMachineName)

Write-Information "Virtual machine '$virtualMachineName' executing user configuration ... " -NoNewLine $true
$userName = $subscription.virtualMachines.adminUserName
$password = $subscription.virtualMachines.password
$netBiosDomain = $subscription.virtualMachines.netBiosDomain
$uri = Get-AzureWinRMUri -ServiceName $virtualMachineService -Name $virtualMachineName
$credential = New-Object System.Management.Automation.PSCredential(($netBiosDomain + "\" + $userName), (ConvertTo-SecureString $password -AsPlainText -Force))
$session = New-PSSession -ComputerName $uri[0].DnsSafeHost -Credential $credential -Port (Get-VirtualMachineInstanceEndpointPort $subscription $virtualMachineName) -UseSSL
foreach ($user in $script.users.user)
{
    $repeat = $false
    do
    {
        try
        {
	        Invoke-Command -Session $session -ScriptBlock {
		        param([string]$ouName, [string]$userName, [string]$password, [string]$userUpn, [string]$firstName, [string]$lastName, [string]$displayName, [string]$manager)
                Import-Module ActiveDirectory
		        $domain = (Get-ADDomain).DistinguishedName
		        if ((Get-ADOrganizationalUnit -Filter { Name -eq $ouName }) -eq $null)
		        {
			        New-ADOrganizationalUnit -Name $ouName -Path $domain
		        }
		        $ou = "OU=$ouName,$domain"
		        $securePassword = ConvertTo-SecureString $password -AsPlainText -Force
		        if ((Get-ADUser -Filter {Name -eq $userName}) -eq $null)
		        {
			        if ([string]::IsNullOrEmpty($displayName))
			        {
				        $displayName = ($firstName + " " + $lastName)
			        }
			        if ([string]::IsNullOrEmpty($manager))
			        {
				        New-ADUser –Name $userName –SamAccountName $userName -UserPrincipalName $userUpn -EmailAddress $userUpn `
						            -AccountPassword $securePassword -PasswordNeverExpires $true -Enabled $true -Path $ou `
						            -GivenName $firstName -Surname $lastName –DisplayName $displayName
			        }
			        else
			        {
				        New-ADUser –Name $userName –SamAccountName $userName -UserPrincipalName $userUpn -EmailAddress $userUpn `
						            -AccountPassword $securePassword -PasswordNeverExpires $true -Enabled $true -Path $ou `
						            -GivenName $firstName -Surname $lastName –DisplayName $displayName -Manager $manager
			        }
		        }
	        } -ArgumentList $script.ou, $user.userName, $user.password, $user.upn, $user.firstName, $user.lastName, $user.displayName, $user.manager
            $repeat = $false
        }
        catch
        {
            $repeat = $_.Exception.Message -eq "Attempting to perform the InitializeDefaultDrives operation on the 'ActiveDirectory' provider failed." -or `
                      $_.Exception.Message -eq "Unable to find a default server with Active Directory Web Services running." -or `
                      $_.Exception.Message -eq "Server instance not found on the given port."
            if ($repeat)
            {
                Start-Sleep 3
            }
            else
            {
                throw $_.Exception.Message
            }
        }
    } while ($repeat)
}
Remove-PSSession $session
Write-Text "done."